/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.teamreinforce.web.controllers;

import com.teamreinforce.ejb.beans.*;
import com.teamreinforce.ejb.entities.*;
import com.teamreinforce.ejb.model.IPerformeCollaborator;
import com.teamreinforce.ejb.model.IPerformeProjects;
import com.teamreinforce.utils.TeamReinforceTimeUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author tidiane
 */
@WebServlet(
                name = "ProjectControllerServlet",
                loadOnStartup = 1,
                urlPatterns = 
                                {
                                    "/creerprojet",
                                    "/creerrisque",
                                    "/modifier-projet", 
                                    "/modifier-etape",
                                    "/modifier-tache",
                                    "/modifier-reunion",
                                    "/supprimer-projet",
                                    "/supprimer-tache",
                                    "/supprimer-reunion",
                                    "/supprimer-collaborateur",
                                    "/projets-list",
                                    "/creer-etape",
                                    "/creer-tache"
                                }
           )

public class ProjectControllerServlet extends HttpServlet {

    @EJB
    private ProjetFacade projectF;
    
    @EJB
    private EtapeFacade etapeF;
    
    @EJB
    private TacheFacade tacheF;
    
    @EJB
    private ReunionFacade reunionF;
    
    @EJB
    private CollaborateurFacade collaborateurF;    
    
    @EJB
    private IPerformeProjects pProjects;
    
    @EJB
    private IPerformeCollaborator pCollaborators;
    
    
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String code = request.getAttribute("code").toString();
        String message = request.getAttribute("message").toString();

        try {

            out.println("<html>");
            out.println("<head>");
            out.println("<link rel =\"stylesheet\" type =\"text/css\" href = \"libs/bootstrap/css/bootstrap.css\" />");
            out.println("<title>Message</title>");            
            out.println("</head>");
            out.println("<body>");
            if ( ! code.equals("error"))
                out.println("<div class=\"alert alert-success\" style = \"padding-top : 60px;\">");
            else
                out.println("<div class=\"alert alert-error\" style = \"padding-top : 60px;\">");
            out.println("<h4 class=\"alert-heading\">" + code +"</h4>");
            out.println(message);
            out.println("</div>");
            out.println("</body>");
            out.println("</html>");
        } 
        finally {            
            out.close();
        }
    }

    /**
     * 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */ 
    protected void prossesAJAXResponse(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String code = request.getAttribute("code").toString();
        String message = request.getAttribute("message").toString();
        
        try {
            out.println(code + " : " + message);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.close();
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userPath = request.getServletPath();
        
        /**
         * Delete a projet : Response to the ajax code
         */
        if ( userPath.equals("/supprimer-projet")){
            try {
                String project = request.getParameter("pid");
                // get the projet
                Projet _project = projectF.find(Integer.parseInt(project));
                
                // delete the project
                projectF.remove(_project);
                request.setAttribute("code", "success");
                request.setAttribute("message", "Mise à jour effectuée avec succes ! \nActualisez la page !");
            }catch (Exception e) {
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                prossesAJAXResponse(request, response);
            }
            prossesAJAXResponse(request, response);
        }
        
        
         /**
         * Delete a reunion : Response to the ajax code
         */ 
        if ( userPath.equals("/supprimer-reunion")){
            try {
                String _reunion = request.getParameter("pid");
                // get the reunion
                Reunion reunion = reunionF.find(Integer.parseInt(_reunion));
                  
                // delete the reunion
                reunionF.remove(reunion);
 
                request.setAttribute("code", "success");
                request.setAttribute("message", "Mise à jour effectuée avec succes ! \nActualisez la page !");
                prossesAJAXResponse(request, response);
            }catch (Exception e) {
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                prossesAJAXResponse(request, response);
            }
        }
        
        
        
        /**
         * Delete a collaborateur : Response to the ajax code
         */
        if ( userPath.equals("/supprimer-collaborateur")){
            try {
                String _collaborateur = request.getParameter("pid");
                // get the collaborateur
                Collaborateur collaborateur = collaborateurF.find(Integer.parseInt(_collaborateur));
                  
                // delete the collaborateur
                collaborateurF.remove(collaborateur);

                request.setAttribute("code", "success");
                request.setAttribute("message", "Mise à jour effectuée avec succes ! \nActualisez la page !");
                prossesAJAXResponse(request, response);
            }catch (Exception e) {
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                prossesAJAXResponse(request, response);
            }
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        
        String userPath = request.getServletPath();
         
        /**
         * Adding a new project
         */
        if ( userPath.equals("/creerprojet")){
            String title = request.getParameter("titre");
            String description = request.getParameter("description");
            String dateDebut = request.getParameter("ddebut");
            String dateFin = request.getParameter("dfin");
            System.out.println("Title : " + title);
            System.out.println("Description : " + description);
            try {
                pProjects.createProject(title, description, dateDebut, dateFin);
                request.setAttribute("code", "success");
                request.setAttribute("message", "Projet crée avec succès !");
            }catch (Exception e){
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                processRequest(request, response);
            }
            
            processRequest(request, response);
        }
         
        /**
         * Add a risque to the project
         */
        if ( userPath.equals("/creerrisque")) {
            try {
                String titre = request.getParameter("projet").toString();
                String risque = request.getParameter("risque").toString();
                String proba = request.getParameter("probabilite").toString();
                String impact = request.getParameter("impact").toString();
                String planB = request.getParameter("plan_b").toString();

                System.out.println(" projet : " + titre);
                System.out.println(" risque : " + risque);
                System.out.println(" proba : " + proba);
                System.out.println(" impact : " + impact);
                System.out.println(" plan " + planB);
                
                Projet projet = pProjects.getProjectByTitle(titre);
                System.out.println(" cool !");
                pProjects.addRisqueToProject(projet, risque, Integer.parseInt(proba), impact, planB);
                
                request.setAttribute("code", "success");
                request.setAttribute("message", "Nouveau risque ajouté avec succès !");
            }catch (Exception e){
                System.err.println(" Err :: " + e.getMessage());
                request.setAttribute("code", "error");
                request.setAttribute("message", "Une erreur");
                System.out.println(" Ex : " + e.getMessage());
                processRequest(request, response);
            }
            processRequest(request, response);
        }
        
        // The code for the step management
        if ( userPath.equals("/creer-etape")){
            String _projet = "";
            try {
                //String titre = request.getParameter("projet");
                String etape = request.getParameter("libelle");
                String dateDebut = request.getParameter("datum1");
                String dateFin = request.getParameter("datum2");
                String description = request.getParameter("description");

                // Get the project
                _projet = getServletContext().getAttribute("projet").toString();
                
                Projet projet = projectF.find(Integer.parseInt(_projet));

                //pProjects.addStepToProject(projet, etape, description, dateDebut, dateFin);
                Etape _etape = new Etape(Integer.SIZE,etape, dateDebut, dateFin);
                _etape.setProjet(projet);
                etapeF.create(_etape);
                
                getServletContext().setAttribute("etapes", projet.getEtapeList());
                
                request.setAttribute("code", "success");
                request.setAttribute("message", "Nouvelle étape ajouté avec succès !");
            }catch (Exception e){
                System.out.println(" Erreur ici !");
                request.setAttribute("code", "erreur");
                request.setAttribute("message", "Une erreur est survenue lors de l'ajout !");
                processRequest(request, response);
            }

            processRequest(request, response);
        }
        
        // The code the task mangement
        if ( userPath.equals("/creer-tache")){
            try {
                String collaborateur = request.getParameter("collaborateur");
                String libelle = request.getParameter("libelle");
                String ddebut = request.getParameter("datum1");
                String dfin = request.getParameter("datum2");
                String description = request.getParameter("description");

                // Getting the stape
                Etape etape = (Etape) getServletContext().getAttribute("etape");
                Collaborateur _collaborateur = pCollaborators.getCollaboratorByLogin(collaborateur);
                Tache task = pProjects.addTaskToStep(etape, libelle, description, ddebut, dfin);
                
                pProjects.assignTaskToCollaborator(_collaborateur, task);
                
                request.setAttribute("code", "success");
                request.setAttribute("message", collaborateur + " a été affecté à la tâche créée!");
            }catch (Exception e){
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                processRequest(request, response);
            }
            processRequest(request, response);
        }
        
        // Update an existing projetcollaborateur
        if ( userPath.equals("/modifier-projet")){
            
            try {
                Projet project = (Projet) request.getServletContext().getAttribute("projet");
                String title = request.getParameter("titre");
                String description = request.getParameter("description");
                String dateDebut = request.getParameter("ddebut");
                String dateFin = request.getParameter("dfin");
                
                // Updating the project
                if ( title != null) project.setTitre(title);
                if ( description != null) project.setDescription(description);
                if ( dateDebut != null) project.setDateDebut(dateDebut);
                if ( dateFin != null) project.setDateFin(dateFin);
                
                projectF.edit(project);
                
                request.setAttribute("code", "success");
                request.setAttribute("message", "Mise à jour effectuée avec succes !");
            }catch (Exception e){
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                processRequest(request, response);
            }
            processRequest(request, response);
        }
        
        /**
         * Edit a step
         */
        if ( userPath.equals("/modifier-etape")){
            try {
                // Get the step to edit
                Etape _etape = (Etape) getServletContext().getAttribute("etape");
                
                String etape = request.getParameter("libelle");
                String dateDebut = request.getParameter("datum1");
                String dateFin = request.getParameter("datum2");
                String description = request.getParameter("description");
                
                if ( etape != null && !etape.equals("")) _etape.setLibelle(etape); 
                if ( dateDebut != null && !dateDebut.equals("")) _etape.setDateDebut(dateDebut);
                if ( dateFin != null && !dateFin.equals("")) _etape.setDateFin(dateFin);
                if ( description != null && !description.equals("")) _etape.setDescription(description);
                
                etapeF.edit(_etape);
                
                request.setAttribute("code", "success");
                request.setAttribute("message", "Mise à jour effectuée avec succes !");
                
            }catch (Exception e){
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                processRequest(request, response);
            }
             processRequest(request, response);
        }
        
        if ( userPath.equals("/modifier-tache")){

            try {
                Tache tache = (Tache) getServletContext().getAttribute("tache");
                String collaborateur = request.getParameter("collaborateur");
                Collaborateur _collaborateur = pCollaborators.getCollaboratorByLogin(collaborateur);
                
                String libelle = request.getParameter("libelle");
                String ddebut = request.getParameter("datum1");
                String dfin = request.getParameter("datum2");
                
                String description = request.getParameter("description");
                
                if ( libelle != null && !libelle.equals("")) tache.setLibelle(libelle);
                
                if ( ddebut != null && !ddebut.equals("")) {
                    tache.setDateDebut(ddebut);
                    tache.setDuree(TeamReinforceTimeUtils.calculateDuration(ddebut, tache.getDateFin()));
                }
                if ( dfin != null && !dfin.equals("")) {
                    tache.setDateFin(dfin);
                    tache.setDuree(TeamReinforceTimeUtils.calculateDuration(tache.getDateDebut(), dfin));
                }
                
                if ( description != null && !description.equals("")) tache.setDescription(description);
                
                tacheF.edit(tache);
                
                request.setAttribute("code", "Confirmation");
                request.setAttribute("message", "Mise à jour effectuée avec succes !");
                
                
            }catch (Exception e){
                request.setAttribute("code", "error");
                request.setAttribute("message", e.getMessage());
                processRequest(request, response); 
            }
            processRequest(request, response); 
        }
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
